<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\work;

use app\common\controller\WorkWechatController;
use app\common\model\platform\Platform;
use app\common\model\system\Config;
use hiduoke\services\workWechat\WorkWechatOpen;
use think\App;
use think\facade\Log;

/**
 * 企业微信开放平台
 * @package app\controller\work
 * User: liuhongbin
 * Date: 2022-12-15 15:08
 */
class Open extends WorkWechatController
{
    /**
     * @var \EasyWeChat\OpenWork\Application|mixed
     */
    private $openApp;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->workWechatOpen = new WorkWechatOpen();
        $this->openApp = $this->workWechatOpen->getOpenApp();
    }

    public function index()
    {
        return $this->success("企业微信相关接口地址");
    }

    // 企业微信授权回调
    public function callBack()
    {
        $plaid = get_plaid();
        $work_wechat = (new Platform())->where(['plaid' => $plaid])->find();
        if (!$work_wechat) {
            return showMessage('出错了，当前企业微信不存在，请重新扫码授权', 'error', '', -1, ['show_btn' => false, 'second' => -1]);
        }
        $auth_code = $this->request->get('auth_code');
        if (!$auth_code) {
            return showMessage('出错了', 'error', '', -1, ['show_btn' => false, 'second' => -1, 'detailed' => '未找到授权码，请重新扫码授权,或者联系管理员']);
        }
        $res = $this->openApp->corp->getPermanentByCode($auth_code); //传入临时授权码
        if (isset($res['permanent_code'])) {
            $config = $work_wechat['config'];
            $config['permanent_code'] = $res['permanent_code'];
            if (isset($res['auth_corp_info']['corpid'])) {
                $config['corp_id'] = $res['auth_corp_info']['corpid'];
                $work_wechat->corp_id = $res['auth_corp_info']['corpid'];
            }
            $work_wechat->auth_type = 1;
            $work_wechat->config = $config;
            $work_wechat->save();
            return showMessage('授权成功', 'success', '', 0, ['show_btn' => false, 'second' => -1, 'title' => '授权成功,请关闭当前页面']);
        } else {
            Log::error('企业微信授权失败：' . json_encode($res));
            return showMessage('授权失败', 'error', '', -1, ['show_btn' => false, 'second' => -1]);
        }
    }


    /**
     * 服务商事件回调地址
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function event()
    {
        try {
            $server = $this->openApp->server;
            $server->push(function ($message) {
                $plaid = 0;
                if (isset($message['ToUserName'])) {
                    $plaid = (new Platform())->where(['corp_id' => $message['ToUserName'], 'auth_type' => 1])->value('plaid');
                }
                //微信客服
                if (isset($message['Event']) && $message['Event'] == 'kf_msg_or_event') {
                    $this->dealWithKefuMsg($message, $plaid);
                }
                $res = (new Config())->getValueByKey("workWechat") ?? [];
                $auto_platform = $res['auto_platform'] ?? 0; // 是否自动创建平台
                $auto_platform_uid = $res['auto_platform_uid'] ?? 1; // 自动创建平台的用户id
                if ($message['InfoType'] == "create_auth" && $auto_platform) {
                    // 自动创建平台
                    $res = $this->openApp->corp->getPermanentByCode($message['AuthCode']); //传入临时授权码
                    if (isset($res['permanent_code'])) {
                        $corpid = $res['auth_corp_info']['corpid'] ?? '';
                        $work_wechat = (new Platform())->where(['corp_id' => $corpid])->find();
                        if (!$work_wechat) {
                            $data = array(
                                'uid'       => $auto_platform_uid,
                                'type'      => 3,
                                'config'    => [
                                    'permanent_code' => $res['permanent_code'],
                                    'corp_id'        => $corpid,
                                ],
                                'auth_type' => 1,
                                'corp_id'   => $corpid,
                                'name'      => $res['auth_corp_info']['corp_name'] ?? ('自动创建' . $corpid),
                                'logo'      => $res['auth_corp_info']['corp_square_logo_url'] ?? '',
                                'status'    => 1,
                            );
                            (new Platform())->save($data);
                        }
                    }
                }
                event('wework_event_message', ['message' => $message, 'plaid' => $plaid]);
            });
            $response = $server->serve();
            $response->send();
        } catch (\Exception $e) {
            Log::write(['work_wechat_open_message_error' => $e->getMessage()]);
        }
    }
}
